#!/bin/bash
set -e
app_url=$1

if [ "$1" = "" ] ; then
	echo "Usage: $0 app_url [nreq]"
	echo "\tnreq number of requests"
	echo "\te.g. $0 /happy will run ab to fetch http://localhost/app/happy and then http://localhost:8000/happy"
	echo "\te.g. $0 / will run ab to fetch http://localhost/app/ and then http://localhost:8000/"
	exit 1
fi

bn=`basename $app_url`
if [ "$bn" = "/" ] ; then
	label="root"
else
	label=$bn
fi
echo $label

apache_url=http://localhost/app${app_url}
django_url=http://localhost:8000${app_url}


if [ "$2" = "" ] ; then
	nreq=500
else
	nreq=$2
fi

apache_qps_file=data/apache_qps_${label}_n${nreq}.dat
django_qps_file=data/django_qps_${label}_n${nreq}.dat

echo "cuser qps" > $apache_qps_file
echo "cuser qps" > $django_qps_file

cuser_range="5 10 15 20 50"
if [ $nreq -gt 99 ] ; then
	cuser_range="5 10 15"
fi

for cuser in $cuser_range
do
	echo "running request for $app_url on apache:nreq $nreq cuser $cuser"
	echo -n "$cuser " >> $apache_qps_file
	ab -k -r -n $nreq -c $cuser -g data/apache.dat $apache_url | grep "Requests per second:" | cut -d" " -f7 >> $apache_qps_file

	echo "running request for $app_url on django:nreq $nreq cuser $cuser"
	echo -n "$cuser " >> $django_qps_file
	ab -k -r -n $nreq -c $cuser -g data/django.dat $django_url  | grep "Requests per second:" | cut -d" " -f7 >> $django_qps_file

	graph_dir=graphs
	mkdir -p $graph_dir

	for i in apache django
	do
		data_file=data/${i}.dat
		output_file=$graph_dir/${i}-${label}-n${nreq}-c${cuser}.png
		gnuplot <<EOF
# set output
set terminal png
set output "${output_file}
# graph title
set title "$i ${label} n${nreq} c${cuser}"
# nicer aspect ratio for image size
set size 1,0.7
# y-axis grid
set grid y
# x-axis label
set xlabel "request"
# y-axis label
set ylabel "time (ms)"
plot "$data_file" using 9 smooth sbezier with lines title "ttime", "$data_file" using 10 smooth sbezier with lines title "wait"
EOF
	done
	mv -f data/apache.dat data/apache-${label}-n${nreq}-c${cuser}.dat
	mv -f data/django.dat data/django-${label}-n${nreq}-c${cuser}.dat
done

qps_output_file=$graph_dir/qps_${label}_n${nreq}.png
gnuplot <<EOF
# set output
set terminal png
set output "${qps_output_file}
# graph title
set title "$qps ${label} n${nreq}"
# nicer aspect ratio for image size
set size 1,0.7
# y-axis grid
set grid y
# x-axis label
set xlabel "cuser"
# y-axis label
set ylabel "qps"
plot "$apache_qps_file" using 1:2 smooth sbezier with lines title "apache", "$django_qps_file" using 1:2 smooth sbezier with lines title "django"
EOF
